<template>
  <view class="page">
    <!-- 表单组件 -->
    <mes-form
      :mesForm="jurisdiction !== 'details' ? mesFormTop : detailForm"
    ></mes-form>
    <!-- 备注 -->
    <mes-form
      :mesForm="jurisdiction !== 'details' ? remark : detailsRemark"
    ></mes-form>
    <!-- 间距 -->
    <view class="bottom-height"></view>
    <!-- 重置 -->
    <mes-button
      :type="3"
      :form="buttonFrom"
      v-if="jurisdiction !== 'details'"
    ></mes-button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      storeHasMore: true,
      storeForm: {
        page: 1,
        limit: 8,
        status:1
      },
      index: '', //当前商品索引
      jurisdiction: '', //是否显示按钮权限
      remark: {
        top: 20,
        row: {
          remark: ''
        },
        items: [
          {
            title: '备注',
            slots: {
              field: 'remark',
              type: 'input'
            }
          }
        ]
      },
      detailsRemark: {
        top: 20,
        row: {
          remark: ''
        },
        items: [
          {
            title: '备注',
            slots: {
              field: 'remark'
            }
          }
        ]
      },
      detailForm: {
        top: 20,
        row: {},
        items: [
          {
            title: '商品编号',
            slots: {
              field: 'goods_code'
            }
          },
          {
            title: '商品名称',
            slots: {
              field: 'goods_name'
            }
          },
          {
            title: '商品单位',
            slots: {
              field: 'unit_name'
            }
          },
          {
            title: '商品属性',
            slots: {
              field: 'attr_name'
            }
          },
          {
            title: '仓库',
            slots: {
              field: 'stores_name'
            }
          },
          {
            title: '可用库存',
            slots: {
              field: 'allow_stock'
            }
          },
          {
            title: '批次',
            slots: {
              field: 'batch_id'
            }
          },
          {
            title: '生产日期',
            slots: {
              field: 'manufacture',
              type: 'date',
              getSerial: (serial) => {
                console.log('选择的序列号', serial)
                this.detailForm.row.serial = serial
                this.detailForm.row.number = serial.length
              }
            }
          },
          {
            title: '保质期(天)',
            slots: {
              field: 'guarantee'
            }
          },
          {
            title: '有效期至',
            slots: {
              field: 'validity',
              type: 'date',
              getSerial: (serial) => {
                console.log('选择的序列号', serial)
                this.mesFormTop.row.serial = serial
                this.mesFormTop.row.number = serial.length
              }
            }
          },
          {
            title: '数量',
            slots: {
              field: 'number'
            }
          },
          {
            title: '基本单位',
            slots: {
              field: 'default_unit_name'
            }
          },
          {
            title: '基本数量',
            slots: {
              field: 'basic_nmber'
            }
          },
          {
            title: '单价',
            slots: {
              field: 'unit_price'
            }
          },
          {
            title: '金额',
            slots: {
              field: 'all_money'
            }
          }
        ]
      },
      mesFormTop: {
        top: 20,
        row: {},
        items: [
          {
            title: '商品编号',
            required: true,
            slots: {
              field: 'goods_code'
              // icon: 'scan'
            },
            rules: [
              {
                // 是否必要
                type: 'required',
                message: '请选择商品编号'
              }
            ]
          },
          {
            title: '商品名称',
            required: true,
            slots: {
              field: 'goods_name'
            },
            rules: [
              {
                // 是否必要
                type: 'required',
                message: '请输入商品名称'
              }
            ]
          },
          {
            title: '商品单位',
            required: true,
            slots: {
              field: 'unit_name',
              icon: 'arrow',
              type: 'select',
              select: {
                placeholder: '请输入关键词',
                options: [],
                changeEvent: (item) => {
                  this.mesFormTop.row.goods_unit = item.id
                  this.mesFormTop.row.unit_name = item.name
                  this.formatInfo('goods_unit')
                }
              }
            },
            rules: [
              {
                // 是否必要
                type: 'required',
                message: '请选择商品单位'
              }
            ]
          },
          {
            title: '商品属性',
            required: true,
            slots: {
              field: 'attr_name',
              icon: 'arrow',
              type: 'select',
              select: {
                placeholder: '请输入关键词',
                options: [],
                changeEvent: (item) => {
                  this.mesFormTop.row.goods_attr = item.id //拿到是个数组
                  this.mesFormTop.row.attr_name = item.name
                }
              }
            },
            rules: [
              {
                // 是否必要
                type: 'required',
                message: '请选择商品属性'
              }
            ]
          },
          {
            title: '仓库',
            slots: {
              field: 'stores_name',
              icon: 'arrow',
              type: 'select',
              showSelect: () => {
                this.resetPaging()
                this.getStores()
              },
              select: {
                search: true,
                placeholder: '请输入关键词',
                options: [],
                searchEvent: (keyword) => {
                  this.getStores(keyword)
                  this.resetPaging()
                },
                scrolltoupper: () => {
                  if (this.storeForm.page > 0) {
                    this.storeForm.page--
                  }
                  this.getStores()
                },
                scrolltolower: () => {
                  if (!this.storeHasMore) return
                  this.storeForm.page++
                  this.getStores()
                },
                changeEvent: (item) => {
                  this.mesFormTop.row.stores_id = item.id
                  this.mesFormTop.row.stores_name = item.name
                }
              }
            }
          },
          {
            title: '可用库存',
            slots: {
              field: 'allow_stock'
              // type: 'input'
            }
          },
          {
            title: '批次',
            slots: {
              field: 'batch_name',
              type: 'batch',
              icon: 'arrow',
              post_form: {
                goods_code: 'goods_code',
                stores_id: 'stores_id',
                goods_attr: 'goods_attr'
              },
              getBatch: (batch) => {
                console.log('选择的批次', batch)
                this.mesFormTop.row.batch_id = batch.batch_id
                this.mesFormTop.row.batch_name = batch.batch_name
                this.mesFormTop.row.manufacture = batch.manufacture
                this.mesFormTop.row.guarantee = batch.guarantee
                this.mesFormTop.row.validity = batch.validity
              }
            }
          },
          {
            title: '生产日期',
            slots: {
              field: 'manufacture',
              type: 'date',
              changeEvent: (e, slots, row) => {
                this.productionChange(e, slots, row)
              },
              getSerial: (serial) => {
                console.log('选择的序列号', serial)
                this.mesFormTop.row.serial = serial
                this.mesFormTop.row.number = serial.length
              }
            }
          },
          {
            title: '保质期(天)',
            slots: {
              field: 'guarantee',
              type: 'input',
              input_type: 'number',
              inputEvent: (e, slots, row) => {
                this.getTime(e, slots, row)
              }
            }
          },
          {
            title: '有效期至',
            slots: {
              field: 'validity',
              type: 'date',
              changeEvent: (e, slots, row) => {
                this.validityChange(e, slots, row)
              },
              getSerial: (serial) => {
                console.log('选择的序列号', serial)
                this.mesFormTop.row.serial = serial
                this.mesFormTop.row.number = serial.length
              }
            }
          },
          {
            title: '数量',
            required: true,

            slots: {
              icon: 'yield',
              field: 'number',
              type: 'serial',
              getSerial: (serial) => {
                console.log('选择的序列号', serial)
                this.mesFormTop.row.serial = serial
                this.mesFormTop.row.number = serial.length
                this.formatInfo('number')
              },
              inputEvent: () => {
                this.formatInfo('number')
              }
            },
            rules: [
              {
                // 是否必要
                type: 'required',
                message: '请输入数量'
              }
            ]
          },
          {
            title: '基本单位',
            slots: {
              field: 'default_unit_name'
              // type: 'input'
            }
          },
          {
            title: '基本数量',
            slots: {
              field: 'basic_nmber',
              type: 'input',
              inputEvent: () => {
                this.formatInfo('basic_nmber')
              }
            }
          },
          {
            title: '单价',
            required: true,
            slots: {
              field: 'unit_price',
              type: 'input',
              input_type: 'digit',
              inputEvent: () => {
                this.formatInfo('unit_price')
              }
            },
            rules: [
              {
                // 是否必要
                type: 'required',
                message: '请输入单价'
              }
            ]
          },
          {
            title: '金额',
            required: true,
            slots: {
              field: 'all_money',
              type: 'input',
              input_type: 'digit',
              inputEvent: () => {
                this.formatInfo('all_money')
              }
            },
            rules: [
              {
                // 是否必要
                type: 'required',
                message: '请输入金额'
              }
            ]
          }
        ]
      },
      buttonFrom: {
        leftEvent: () => {
          getApp().globalData.goods.list.splice(this.index, 1)
          uni.navigateBack({ delta: 1 })
        },
        leftText: '删除',
        rightEvent: () => {
          getApp().globalData.goods.list[this.index] = Object.assign(
            this.mesFormTop.row,
            this.remark.row
          )
          uni.navigateBack({ delta: 1 })
        },
        rightText: '保存'
      }
    }
  },
  methods: {
    // 生产日期时间选择器改变
    productionChange(e, slots, row) {
      // 计算保质期
      if (row.validity) {
        let date2 = new Date(row.validity)
        let date1 = new Date(e)
        let timeStamp1 = Date.parse(date1)
        let timeStamp2 = Date.parse(date2)
        let sub = timeStamp2 - timeStamp1
        if (sub < 0) {
          this.mesFormTop.row.validity = ''
          this.mesFormTop.row.guarantee = ''
        } else {
          let day = Math.floor(sub / (24 * 60 * 60 * 1000))
          this.mesFormTop.row.guarantee = day
        }
      }
    },
    // 有效期时间改变
    validityChange(e, slots, row) {
      let validity = e
      // 计算保质期
      if (row.manufacture) {
        let date2 = new Date(validity)
        let date1 = new Date(row.manufacture)
        let timeStamp1 = Date.parse(date1)
        let timeStamp2 = Date.parse(date2)
        let sub = timeStamp2 - timeStamp1

        if (sub < 0) {
          this.mesFormTop.row.manufacture = ''
          this.mesFormTop.row.guarantee = ''
          console.log()
        } else {
          let day = Math.floor(sub / (24 * 60 * 60 * 1000))
          this.mesFormTop.row.guarantee = day
        }
      }
    },
       // 计算保质期
       getTime(e, slots, row) {
      if (row.validity != '' && row.manufacture != '') {
        let date2 = new Date(row.manufacture)
        let date1 = Number(row.guarantee) * 86400000
        let timeStamp2 = Date.parse(date2)
        let sub = timeStamp2 + date1
        if (sub > 0) {
          let now = new Date(sub)
          let year = now.getFullYear()
          let month = now.getMonth() + 1
          let day = now.getDate()
          this.mesFormTop.row.validity = year + '-' + month + '-' + day
        }
      }
      // 计算保质期
      if (row.validity != '' && row.guarantee != '') {
        let date2 = new Date(row.validity)
        let date1 = Number(row.guarantee) * 86400000
        let timeStamp2 = Date.parse(date2)
        let sub = timeStamp2 - date1
        if (sub > 0) {
          let now = new Date(sub)
          let year = now.getFullYear()
          let month = now.getMonth() + 1
          let day = now.getDate()
          this.mesFormTop.row.manufacture = year + '-' + month + '-' + day
        }
      }
      if (row.manufacture != '' && row.guarantee != '') {
        let date2 = new Date(row.manufacture)
        let date1 = Number(row.guarantee) * 86400000
        let timeStamp2 = Date.parse(date2)
        let sub = timeStamp2 + date1
        if (sub > 0) {
          let now = new Date(sub)
          let year = now.getFullYear()
          let month = now.getMonth() + 1
          let day = now.getDate()
          this.mesFormTop.row.validity = year + '-' + month + '-' + day
        }
      }
    },
    //获取商品属性
    getProperty() {
      let form = {
        id:
          getApp().globalData.goods.list[this.index].goods_id ||
          getApp().globalData.goods.list[this.index].id
      }
      this.$api.source.goods.getgoodsauxiliary(form).then((res) => {
        if (res.code == 200) {
          res.data.auxiliary_data= res.data.auxiliary_data? res.data.auxiliary_data:[]
          res.data.auxiliary_data.forEach((item) => {
            item.id = item.attribute_id
            item.name = item.attr_name
          })
          this.mesFormTop.items[3].slots.select.options =
            res.data.auxiliary_data
          let goods_attr = ''
          let attr_name = ''
          goods_attr = getApp().globalData.goods.list[this.index].goods_attr //拿到是个数
          let arr = res.data.auxiliary_data.filter((item) => {
            let id =
              this.jurisdiction == 'details'
                ? this.detailForm.row.goods_attr
                : this.mesFormTop.row.goods_attr
            return item.attribute_id == id
          })
          attr_name = arr.length > 0 ? arr[0].attr_name : null
          if (this.jurisdiction == 'details') {
            this.detailForm.row.goods_attr = goods_attr
            this.detailForm.row.attr_name = attr_name
          } else {
            this.mesFormTop.row.goods_attr = goods_attr
            this.mesFormTop.row.attr_name = attr_name
          }
        }
      })
    },
    resetPaging() {
      this.storeHasMore = true
      this.storeForm.page = 1
      this.mesFormTop.items.forEach((item) => {
        if (item.title == '仓库') {
          item.slots.select.options = []
        }
      })
    },
    //获取仓库列表
    getStores(keyword, newId) {
      this.storeForm.keyword = keyword
      this.$api.source.stores.index(this.storeForm).then((res) => {
        res.data.list.forEach((item) => {
          if (item.id == newId) {
            this.jurisdiction !== 'details'
              ? (this.mesFormTop.row.stores_name = item.name)
              : (this.detailForm.row.stores_name = item.name)
          }
        })
        if (res.code == 200) {
          this.storeHasMore = res.data.list.length ? true : false
          this.mesFormTop.items.forEach((item) => {
            if (item.title === '仓库') {
              item.slots.select.options = [
                ...item.slots.select.options,
                ...res.data.list
              ]
            }
          })
        }
      })
    },
    // 获取变动价格
    async formatInfo(now_field) {
      const postForm = {
        // 商品编号
        goods_code: this.mesFormTop.row.goods_code || null,
        // 商品属性ID（无属性请传空）
        goods_attr: '',
        // 商品单位ID
        goods_unit:
          this.mesFormTop.row.goods_unit || this.mesFormTop.row.unit_id|| null,
        // 仓库ID
        store: '',
        // 数量
        number: this.mesFormTop.row.number|| null,
        // 商品单价
        unit_price: this.mesFormTop.row.unit_price|| null,
        // 商品含税单价
        tax_included: this.mesFormTop.row.unit_price || null,
        // 折扣率
        discount: '',
        // 折扣额
        dis_money: '',
        // 购货金额
        all_money: this.mesFormTop.row.all_money|| null,
        // 税率
        tax_rate: 0,
        // 税额
        tax_money: '',
        // 价税合计
        money_tax_price: this.mesFormTop.row.all_money|| null,
        // 当前变动字段
        now_field:now_field?now_field:null
      }
      const res = await this.$api.buy.common.formatInfo(postForm)
      if (res.code == 200) {
        this.mesFormTop.row.number = res.data.number
        this.mesFormTop.row.unit_price = res.data.unit_price
        this.mesFormTop.row.all_money = res.data.number * res.data.unit_price
        this.mesFormTop.row.basic_nmber = res.data.basic_nmber
      }
    }
  },
  async onLoad(option) {
    this.getStores(null, this.detailForm.row.stores_id)
    let newObj = JSON.parse(option.obj)
    this.jurisdiction = newObj.name //商品是否有编辑删除权限
    this.index = newObj.index
    //
    console.log(
      getApp().globalData.goods.list[this.index].serial_status,
      '判断序列号'
    )
    this.mesFormTop.items[10].slots.icon =
      getApp().globalData.goods.list[this.index].serial_status == 1
        ? 'yield'
        : ''
    if (getApp().globalData.goods.list[this.index].batch != 1) {
      this.mesFormTop.items.splice(6, 4)
      if (this.jurisdiction == 'details') {
        this.detailForm.items.splice(6, 4)
      }
    }
    //判断是否是属性商品
    if (getApp().globalData.goods.list[this.index].auxiliary != 1) {
      this.mesFormTop.items.splice(3, 1)
      if (this.jurisdiction == 'details') {
        this.detailForm.items.splice(3, 1)
      }
    } else {
      this.getProperty() //获取属性列表
    }

    this.jurisdiction == 'details'
      ? (this.detailForm.row = getApp().globalData.goods.list[this.index])
      : (this.mesFormTop.row = getApp().globalData.goods.list[this.index])
    //商品备注
    this.jurisdiction == 'details'
      ? (this.detailsRemark.row.remark =
          getApp().globalData.goods.list[this.index].remark)
      : (this.remark.row.remark =
          getApp().globalData.goods.list[this.index].remark)

    // 获取商品单位
    if (this.jurisdiction !== 'details') {
      this.getStores(null, this.mesFormTop.row.stores_id)

      this.mesFormTop.items[2].slots.select.options = await this.$tools.getUnit(
        this.mesFormTop.row.goods_id || this.mesFormTop.row.id
      )
    } else {
      this.getStores(null, this.detailForm.row.stores_id)
    }
    this.mesFormTop.row.basic_nmber=this.mesFormTop.row.number
  }
}
</script>

<style lang="less" scoped>
</style>
